from visualization import drawscaled
import os
import fnmatch
import cv2
from imageReader import getPanoramicImage, writeReportImage

def left():
    return 1253
def right():
    return 1753
def top():
    return 515
def bottom():
    return 1344

def drawIncisorBox(img):
    topLeft = (left(), top())
    topRight = (right(), top())
    bottomLeft = (left(), bottom())
    bottomRight = (right(), bottom())
    cv2.line(img, topLeft, topRight, 254, thickness = 3)
    cv2.line(img, bottomLeft, bottomRight, 254, thickness = 3)
    cv2.line(img, topLeft, bottomLeft, 254, thickness = 3)
    cv2.line(img, topRight, bottomRight, 254, thickness = 3)
    drawscaled(img,4)
    
def getLeftMostNonBlackColumn(image):
    for j in range(0,image.shape[1]-1):
        for i in range(0,image.shape[0]-1):
            if(image[i,j] > 0):
                return j
    return -1

def getTopMostNonBlackRow(image):
    for i in range(0,image.shape[0]-1):
        for j in range(0,image.shape[1]-1):
            if(image[i,j] > 0):
                return i
    return -1

def getRightMostNonBlackColumn(image):
    for j in range(image.shape[1]-1,-1,-1):
        for i in range(0,image.shape[0]-1):
            if(image[i,j] > 0):
                return j
    return -1

def getBottomMostNonBlackRow(image):
    for i in range(image.shape[0]-1,-1,-1):
        for j in range(0,image.shape[1]-1):
            if(image[i,j] > 0):
                return i
    return -1

def getIncisorBoundary(img):
    left = 999999
    right = 0
    top = 999999
    bottom = 0
    for row in range(0, img.shape[0]-1):
        for col in range(0, img.shape[1] -1):
            if(img[row,col] > 0):
                if col < left:
                    left = col
                if col > right:
                    right = col
                if row < top:
                    top = row
                if row > bottom:
                    bottom = row
    return (left, right, top, bottom)
            

def getIncisorArea():
    left = 999999
    right = 0
    top = 999999
    bottom = 0
    for filename in fnmatch.filter(os.listdir("Panoramic images/segmented"),'*.png'):
        img = cv2.imread("Panoramic images/segmented/"+filename)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        (curLeft, curRight, curTop, curBot) = getIncisorBoundary(img)
        if curLeft != -1 and curLeft < left:
            left = curLeft
        if curRight != -1 and curRight > right:
            right = curRight
        if curTop != -1 and curTop < top:
            top = curTop
        if curBot != -1 and curBot > bottom:
            bottom = curBot
    return (left, right, top, bottom)

